<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>指定区域弹窗</title>
    <link rel="stylesheet" type="text/css" href="../../static/h-ui/css/H-ui.min.css"/>
    <link rel="stylesheet" type="text/css" href="../../lib/Hui-iconfont/1.0.8/iconfont.css"/>
    <link rel="stylesheet" type="text/css" href="../../static/h-ui.admin/skin/default/skin.css" id="skin"/>
    <link rel="stylesheet" type="text/css" href="../../lib/Validform/5.3.2/style.css"/>
    <link rel="stylesheet" type="text/css" href="../../static/h-ui.admin/css/style.css"/>
    <style>
        /*设置区域*/
        .area-warp {
            padding: 10px 5px;
            margin: 10px 5px;
        }

        .area-title {
            margin-bottom: 10px;
        }

        #area-province, #area-city {
            float: left;
            width: 158px;
            overflow-y: scroll;
            height: 150px;
            border: 1px solid #DDDDDD;
            background-color: #FFFFFF;
            padding: 5px;
        }

        #area-city {
            display: none;
            margin-left: 10px;
        }

        .area-content {
            display: none;
        }
    </style>
</head>
<body>
<div class="area-warp">
    <div class="area-title">
                <span style="margin-right: 30px" id="all_country">
                     <input id="country" type="radio" name="area-radio" style="margin-right: 5px" value="0" checked>全国
                </span>
        <span>
                     <input id="area" type="radio" name="area-radio" style="margin-right: 5px" value="1">指定区域
                 </span>
    </div>
    <div class="area-content" style="overflow: hidden;display: none">
        <ul id="area-province">
            <li style="cursor: pointer">
                <!-- <input type="checkbox" class="input-checked mr-5">陕西-->
            </li>
        </ul>
        <ul id="area-city">
            <li style="cursor: pointer">
                <!--<input type="checkbox" class="input-checked mr-5">陕西-->
            </li>
        </ul>
    </div>
    <div style="position: absolute;top:280px;left:170px">
        <input type="button" class="btn radius size-S ml-10 mr-10" value="取&nbsp;&nbsp;消" id="cancelBtn">
        <input type="button" class="btn btn-secondary radius size-S" value="确&nbsp;&nbsp;认" id="sureBtn">
    </div>
</div>
<script type="text/javascript" src="../../lib/jquery/1.9.1/jquery.min.js?rev=@@hash"></script>
<script type="text/javascript" src="../../lib/layer/2.4/layer.js?rev=@@hash"></script>
<script type="text/javascript" src="../../ht-js/public.js?rev=@@hash"></script>
<script>
    var appointArea = {
        isAllCountry: '',
        handleData: [],
        channelId:'',
        providerId:'',
        provinceAry:[],//省
        city:[],//市
        init: function () {
            if(getQueryString("channelId") || getQueryString("providerId")){
                this.channelId = getQueryString("channelId");
                this.providerId = getQueryString("providerId");
                var sessionAreasData = sessionStorage.getItem('saleAreas');
                appointArea.handleData = JSON.parse(sessionAreasData)?JSON.parse(sessionAreasData):[];
                /*console.log(appointArea.handleData,'kkkkk')*/
                this.findProviderChannelIdAreasInfo();
            }else{
                this.onReceiveParamsHandler();
            }

            this.addClick();
        },
        onReceiveParamsHandler: function () {
            var sessionAreasData = sessionStorage.getItem('saleAreas');
            if (sessionAreasData != 'null') {
                if (JSON.parse(sessionAreasData)[0].code == 0) {
                    $('input[name="area-radio"]:first').attr('checked', 'true');
                    $('.area-content').hide();
                } else {
                    $('input[name="area-radio"]:last').attr('checked', 'true');
                    $('.area-content').show();
                    appointArea.handleData = JSON.parse(sessionAreasData);
                }
            }
            appointArea.cityInfo(0, 1);
        },
        addClick: function () {
            // 全国/指定区域
            $('input[name="area-radio"]').on('click', function () {
                var type = $(this).val();// 0 是全国  1是区域
                if (type == 0) {
                    $('.area-content').hide();
                } else {
                    $('.area-content').show();
                }
            });
            // 省- input事件
            $('#area-province').delegate(' li input', 'click', function () {
                var checkFlag = $(this).prop('checked')
                var code = $(this).val();
                var name = $(this).attr('data-name')
                var obj = {
                    code: code,
                    name: name,
                    children:[]
                }
                if (checkFlag) {
                    appointArea.handleData.push(obj);
                    appointArea.cityInfo(code, 2);
                    $('#area-city').show();

                } else {
                    $('#area-city').hide();
                    appointArea.handleData = appointArea.handleData.filter(function (item) {
                        return item.code != code
                    })
                }
            });
            // 省 - 文字事件
            $('#area-province').delegate('li .item-value', 'click', function () {
                var code = $(this).prev().val();
                var inputCheck = $(this).prev().is(':checked');
                if(getQueryString("channelId") && !appointArea.isAllCountry){
                    appointArea.renderChannelCityAreaData(code)
                }else{
                    appointArea.cityInfo(code,2);
                }

                $('#area-city').show();
            });
            // 市 - input事件
            $('#area-city').delegate('li input', 'click', function () {
                var code = $(this).val();
                var parentCode = $(this).attr('data-parent');
                var checkFlag = $(this).prop('checked');
                var name = $(this).attr('data-name');
                if(checkFlag){
                    if(appointArea.handleData.length <=0){
                        var obj = {
                            code:parentCode,
                            name:'',
                            children:[
                                {
                                    name:name,
                                    code:code
                                }
                            ]
                        };
                        appointArea.handleData.push(obj)
                    }else{
                        var ary = appointArea.handleData.filter(function(item){
                            return parentCode == item.code;
                        });
                        if(ary.length > 0){
                            $.each(appointArea.handleData,function(index,item){
                                if(item.code == ary[0].code){
                                    item.children.push({
                                        name:name,
                                        code:code
                                    })
                                }
                            })
                        }else{
                            var obj = {
                                name:'',
                                code:parentCode,
                                children:[{
                                    name:name,
                                    code:code
                                }]
                            };
                            appointArea.handleData.push(obj)
                        }
                    }

                    // 添加页面效果
                    $.each($('#area-province li input'),function(index,item){
                        var inputCode = $(item).val();
                        var inputName = $(item).attr('data-name');
                        if(inputCode == parentCode){
                            $(item).prop('checked',true);
                            $.each(appointArea.handleData,function(index,itm){
                                if(itm.code == parentCode){
                                    itm.name = inputName
                                }else{
                               /*     appointArea.handleData.push({
                                        name:inputName,
                                        code:inputCode,
                                        /!*children:[{
                                            name:name,
                                            code:code
                                        }]*!/
                                    })*/
                                }
                            })
                        }
                    })
                }else{
                    $.each(appointArea.handleData,function(index,item){
                        if(item.code == parentCode){
                            item.children = item.children.filter(function(itm,index){
                                return itm.code != code
                            });
                        }
                    });
                    // console.log(appointArea.handleData,'handleshuju')
                    $.each($('#area-province li input'),function(index,item){
                        var code = $(item).val();
                        var name = $(item).attr('data-name');
                        if(appointArea.handleData.length > 0){
                            $.each(appointArea.handleData,function(index,itm){
                                if(itm.code == code){
                                    if(itm.children.length <=0){
                                        appointArea.handleData = appointArea.handleData.filter(function(item1){
                                            return item1.code != parentCode
                                        })
                                        $(item).prop('checked',false)
                                    }
                                }
                            })
                        }else{
                            $(item).prop('checked',false)
                        }

                    })
                }
                //console.log(appointArea.handleData,'handleshuju111111111')
            });
            // 确认操作
            $('#sureBtn').unbind().on('click', function () {
                var saleAreas = [
                    {
                        code: "0",
                        name: "全国",
                        children: null
                    }
                ];
                if ($('input[name="area-radio"]:checked').val() == 1) {
                    saleAreas = appointArea.handleData;
                    saleAreas = saleAreas.filter((item) => {
                        return item.code != 0;
                    })
                    if(appointArea.handleData.length <=0){
                        return layer.msg('请选择指定区域');
                    }
                }
                var myEvent = new CustomEvent('saveSaleAreasEvent', {
                    detail: { saleAreas },
                });
                window.parent.document.dispatchEvent(myEvent);
                parent.layer.close(parent.layer.index)
            });
            // 取消操作
            $('#cancelBtn').unbind().on('click', function () {
                var index = parent.layer.index;
                parent.layer.close(index)
            })
        },
        cityInfo: function (code, level) {
            var params = {
                parentCode: code
            }
            var succCallBack = function (data) {
                if (data.code == 0) {
                    var result = data.data;
                    appointArea.renderData(result, level);
                }
            }
            return web.doAjax(root.serviceProviderManagement.findAddressList, 'post', params, succCallBack);
        },
        renderData: function (data, level) {
            var str = '';
            $.each(data, function (index, item) {
                str += '<li style="cursor: pointer">' +
                    '                <input  data-parent="' + item.parent_code + '"  data-name="' + item.name + '" type="checkbox" class="input-checked mr-5" value="' + item.code + '" >' +
                    '                <span  data-parent="' + item.parent_code + '" class="item-value" data-id="' + item.code + '">' + item.name + '</span>' +
                    '            </li>';
            });
            if (level == 1) {
                $('#area-province').html(str);
                if(appointArea.handleData.length > 0){
                   $.each($('#area-province li input'),function(index,item){
                       var itemCode = $(item).val();
                        $.each(appointArea.handleData,function(index,itm){
                            if(itemCode == itm.code){
                                $(item).prop('checked',true)
                            }
                        })
                   })
                }
            } else {
                $('#area-city').html(str);
                var flag = false;
                $.each(appointArea.handleData,function(index,item){
                    if(data[0].parent_code == item.code){
                       if(item.children.length >0){
                           return flag = false
                       }else{
                           return flag = true;
                       }
                    }
                })
                if(flag){
                    appointArea.parameterHandleData(data)
                }
                appointArea.renderHandleData(appointArea.handleData)

            }
        },
        // 组装渲染数据
        renderHandleData: function (data) {
            $.each($('#area-city li input'), function (index, item) {
                var code = $(item).val();
                var parentCode = $(item).attr('data-parent')
                $.each(data, function (index, itm) {
                    var initCode = itm.code;
                    if (parentCode == initCode) {
                        $.each(itm.children, function (index, item2) {
                            if (code == item2.code) {
                                $(item).prop('checked', true)
                            }
                        })
                    }

                })
            })
        },
        // 组装参数数据
        parameterHandleData:function(data){
            var ary = [];
            $.each(data, function (index, item) {
                $.each(appointArea.handleData, function (index, itm) {
                    if (itm.code == item.parent_code) {
                        var obj = {
                            name: item.name,
                            code: item.code
                        };
                        ary.push(obj);
                        itm.children = ary
                    }
                })
            });
        },

        // 根据渠道查询指定区域
        findProviderChannelIdAreasInfo:function(){
            var params = {
                providerId:appointArea.providerId,
                channelId:appointArea.channelId
            }
            var succCallBack = function(data){
                if(data.code == 0){
                    var result = data.data
                    if (result[0].saleAreas[0].code == 0) {
                        appointArea.isAllCountry = true;
                    } else {
                        appointArea.isAllCountry = false;
                    }
                    var provinceAry = [];
                    var city = [];
                    // 排除全国
                    if(result && result[0].saleAreas[0].code != 0){
                        $.each(result[0].saleAreas,function(index,item){
                            var obj = {
                                code:item.code,
                                name:item.name,
                                parent_code:''
                            }
                            provinceAry.push(obj);
                            if(item.children){
                                $.each(item.children,function(index,itm){
                                    var obj = {
                                        code:itm.code,
                                        name:itm.name,
                                        parent_code:item.code
                                    };
                                    city.push(obj)
                                })
                            }
                        });
                        appointArea.provinceAry = provinceAry;
                        appointArea.city = city;
                        appointArea.renderChannelProvinceAreaData(provinceAry)
                    }else{
                        appointArea.onReceiveParamsHandler();
                    }
                }else{
                    layer.msg(data.msg)
                }
            }
            return web.doAjax(root.serviceProviderManagement.findProviderCooperationByProviderIdAndChannelId, 'post', params, succCallBack);
        },
        renderChannelProvinceAreaData:function(data){
            if(data[0].code !== 0){
                $('#all_country').hide();
                $('#area').prop('checked',true);
                $('.area-content').show();
            }
            var str = '';
            $.each(data, function (index, item) {
                str += '<li style="cursor: pointer">' +
                    '                <input  data-parent="' + item.parent_code + '"  data-name="' + item.name + '" type="checkbox" class="input-checked mr-5" value="' + item.code + '" >' +
                    '                <span  data-parent="' + item.parent_code + '" class="item-value" data-id="' + item.code + '">' + item.name + '</span>' +
                    '            </li>';
            });
            $('#area-province').html(str);
            if(appointArea.handleData && appointArea.handleData.length > 0){
                $.each($('#area-province li input'),function(index,item){
                    var itemCode = $(item).val();
                    $.each(appointArea.handleData,function(index,itm){
                        if(itemCode == itm.code){
                            $(item).prop('checked',true)
                        }
                    })
                })
            }
        },
        renderChannelCityAreaData:function(code){
            var data = appointArea.city;
            var ary = data.filter(function(item){
                return item.parent_code == code;
            });
            var str = '';
            $.each(ary, function (index, item) {
                str += '<li style="cursor: pointer">' +
                    '                <input  data-parent="' + item.parent_code + '"  data-name="' + item.name + '" type="checkbox" class="input-checked mr-5" value="' + item.code + '" >' +
                    '                <span  data-parent="' + item.parent_code + '" class="item-value" data-id="' + item.code + '">' + item.name + '</span>' +
                    '            </li>';
            });
            $('#area-city').html(str);
            $('#area-city').show();
            var flag = false;
            $.each(appointArea.handleData,function(index,item){
                if(data[0].parent_code == item.code){
                    if(item.children.length >0){
                        return flag = false
                    }else{
                        return flag = true;
                    }
                }
            })
            if(flag){
                appointArea.parameterHandleData(data)
            }
            appointArea.renderHandleData(appointArea.handleData)
        }

    }
    appointArea.init();
</script>
</body>
</html>